<template>
  <el-upload
      ref="ExcelToSql"
      class="upload-demo"
      :action="''"
      :limit="1"
      :on-exceed="handleExceedExcelToSql"
      :auto-upload="false"
      :headers="headers"
      :before-upload="uploadExcelToSql"
  >
    <template #trigger>
      <el-button type="primary" :loading="loading">选择文件</el-button>
    </template>
    <el-button style="margin-left: 1rem" :loading="loading" type="success" @click="submitUploadExcelToSql">
      生成SQL
    </el-button>
    <template #tip>
      <div class="el-upload__tip text-red">
        每次选择一个文件
      </div>
    </template>
  </el-upload>
</template>

<script>
import {ref,unref, getCurrentInstance, watch, reactive, onMounted} from "vue";
import {ElMessage, ElMessageBox, genFileId} from 'element-plus';
import {useRouter} from "vue-router";
import * as XLSX from "xlsx";

export default {
  name: "index",
  components:{

  },
  setup(props ,content){
    const router = useRouter()
    const {proxy} = getCurrentInstance();

    const ExcelToSql = ref()
    let data = {
      form: ref({}),
      loading: ref(false),
      headers: ref({
        Authorization: window.localStorage.getItem("javawebtoken"),
        responseType: 'blob',
        "Content-Type": "application/json",
      }),
    }
    //监听
    watch(() => [props.info], ([newInfo],[oldInfo]) => {

    })
    onMounted(async () => {

    })
    let methods = {
      /**
       * 选择文件时触发
       * */
      handleExceedExcelToSql(files, fileList) {
        ExcelToSql.value.clearFiles()
        let file = files[0]
        file.uid = genFileId()
        ExcelToSql.value.handleStart(file)
      },
      submitUploadExcelToSql() {
        ExcelToSql.value.submit()
      },

      /**
       * 上传文件操作
       * */
      uploadExcelToSql(file) {
        console.log(file)

        // 监听文件上传前事件
        const fileType = file.name.split('.').pop();
        const allowTypes = ['xlsx', 'xls'];
        if (allowTypes.indexOf(fileType) === -1) {
          this.$message.error(`只能上传 ${allowTypes.join(' 或 ')} 格式的文件`);
          return false;
        }

        // 处理 sheet 页数据
        const reader = new FileReader();
        reader.onload = (e) => {
          const bstr = e.target.result;
          const workbook = XLSX.read(bstr, { type: 'binary', cellDates: true });
          const sheetNames = workbook.SheetNames;
          if (!sheetNames) {
            this.$message.error('上传文件格式不正确，无法读取 Sheet 页');
            return false;
          }
          const sheetName = sheetNames[0];
          const sheet = workbook.Sheets[sheetName];
          const data = XLSX.utils.sheet_to_json(sheet, { defval: '' });

          // 生成 SQL 语句
          const columns = Object.keys(data[0]);
          const columnDefinitions = columns
              .map((column) => {
                const columnData = data.find((row) => row[column] !== undefined);
                const columnDataType = typeof columnData[column] === 'number' ? ' INT' : ' VARCHAR(255)';
                return `${column} ${columnDataType}`;
              })
              .join(',\n');
          const tableName = sheetName.replace(/\s+/g, '_');
          const sql = `CREATE TABLE ${tableName} (\n${columnDefinitions}\n);`;
          console.log(sql);
        };

        reader.onerror = (event) => {
          console.error('FileReader error:', event);
        };

        reader.readAsBinaryString(file);

        // 将文件添加到文件列表
        // fileList.push(file);
        // return false;
      },
    }

    return {
      proxy,
      router,
      ExcelToSql,
      ...data,
      ...methods
    }
  }
}
</script>

<style lang="scss" scoped>

</style>